﻿using OL.FrameCore.Application.CommonData.Dto;
using OL.FrameCore.Application.Dept;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using OL.FrameCore.Application.Module;

namespace OL.FrameCore.Application.CommonData
{
    public class CommonDataService: ICommonDataService
    {
        IDeptService _deptService;
        IModuleService _moduleService;
        public CommonDataService(IDeptService deptService, IModuleService moduleService)
        {
            _deptService = deptService;
            _moduleService = moduleService;
        }

        /// <summary>
        /// 获取部门下拉列表
        /// </summary>
        /// <returns></returns>
        public IList<DropDownModel> GetDeptDropDownList()
        {
            //todo 加缓存

            var listDept = _deptService.GetAllDeptList();

            IList<DropDownModel> list = new List<DropDownModel>();
            foreach (var li in listDept)
            {
                list.Add(new DropDownModel
                {
                    Id = li.Id,
                    Name = li.DeptName,
                    ParentId = li.ParentId,
                    Level = li.DeptLevel
                });
            }

            var result = GetDropDownList(list, 0, "");

            return result;

        }

        /// <summary>
        /// 获取模块下拉列表
        /// </summary>
        /// <returns></returns>
        public IList<DropDownModel> GetModuleDropDownList()
        {
            //todo 加缓存

            var listDept = _moduleService.GetAllModuleList();

            IList<DropDownModel> list = new List<DropDownModel>();
            foreach (var li in listDept)
            {
                list.Add(new DropDownModel
                {
                    Id = li.Id,
                    Name = li.ModuleName,
                    ParentId = li.ParentId,
                    Level = 0
                });
            }

            var result = GetDropDownList(list, 0, "");

            return result;
        }

        /// <summary>
        /// 获取下拉 递归处理树形下拉
        /// </summary>
        /// <param name="list"></param>
        /// <param name="parentId"></param>
        /// <param name="head"></param>
        /// <returns></returns>
        private IList<DropDownModel> GetDropDownList(IList<DropDownModel> list, int parentId, string head)
        {
            List<DropDownModel> result = new List<DropDownModel>();
            var listTmp = list.Where(p => p.ParentId == parentId).ToList();
            foreach (var li in listTmp)
            {
                li.Name = head + li.Name;
                result.Add(li);
                result.AddRange(GetDropDownList(list, li.Id, head + ".... "));
            }
            return result;
        }
    }
}
